package com.guigu.tms.security.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.guigu.tms.security.service.ICustomerLoginService;
import com.guigu.tms.security.service.SendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class CustomerLoginService implements ICustomerLoginService {

    @Autowired
    SendService sendService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String key="customerPhone";

    @Override
    public Integer getValidateCode(String phone) {
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        //发送验证码
        String msg="【短信宝】您的验证码是"+code+",30秒内有效";
        String res=sendService.sendSms("wkj333","77ca3217e5694aa98b230b81a4e03c85",phone,msg);
        if(res.equals("51")){
            return -1;
        }
        //将验证码保存在redis
        redisTemplate.opsForValue().set(key+phone,code,Duration.ofMinutes(1));
        return 1;
    }

    @Override
    public Integer login(String phone, String value) {
        //判断验证码是否失效
        if(!redisTemplate.hasKey(key+phone)){
            return -1;
        }
        //从redis获取验证码
        String value1 = redisTemplate.opsForValue().get(key + phone);
        //判断验证码是否正确
        if(value1.equals(value)){
            redisTemplate.delete(key+phone);
            return 1;
        }
        return 0;
    }
}
